package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.ex.CustomerException;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author ghy
 * @version v1.0
 * create on 2022/11/18 12:02
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     *
     * @param category 实体，因为后面有其他功能也需要调用该接口
     * @return
     */
    @GetMapping("/list")
    public R list(Category category){
        return categoryService.findList(category);
    }

    /**
     * 更新
     * @return
     */
    @PutMapping
    public R modify(@RequestBody Category category){
        return categoryService.modify(category);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping
    public R deleteById(Long id){
        return categoryService.deleteById(id);
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize){
        IPage<Category> ipage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> lqw = Wrappers.<Category>lambdaQuery().orderByAsc(Category::getSort);
        categoryService.page(ipage, lqw);
        return R.success(ipage);
    }

    /**
     * 新增
     * @param category
     * @return
     */
    @PostMapping
    public R add(@RequestBody Category category){
        log.warn("add: {}", category);
        Category dbCategory = categoryService.getOne(Wrappers.<Category>lambdaQuery().eq(Category::getName, category.getName()));
        if(dbCategory != null) {
            throw new CustomerException("分类名称已存在，请更换!!");
        }
        categoryService.save(category);
        return R.success("新增套餐成功");
    }


}
